package com.android.djlmapp.activity.kaika;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.web.ForgetPwdActivity;
import com.android.djlmapp.activity.kaika.web.LianTongXieYiListActivity;
import com.android.djlmapp.activity.kaika.web.PaySuccessActivity;
import com.android.djlmapp.activity.order.OrderListActivity;
import com.android.djlmapp.activity.recharge.AddMoneyActivity;
import com.android.djlmapp.adapter.dialog.GetSimNumAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.listener.LocationCallBack;
import com.android.djlmapp.model.eventbus.FaceRzInfo;
import com.android.djlmapp.model.eventbus.SeleTcInfo;
import com.android.djlmapp.model.home.Info;
import com.android.djlmapp.model.home.LocationInfo;
import com.android.djlmapp.model.kaika.SimNumInfo;
import com.android.djlmapp.popupwindow.CommonPopupWindow;
import com.android.djlmapp.popupwindow.CommonPopupWindow.LayoutGravity;
import com.android.djlmapp.tools.global.Constants;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.GlobalUtils;
import com.android.djlmapp.tools.global.MD5Util;
import com.android.djlmapp.tools.global.MyActivityManager;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.tools.login.OnceLocationTools;
import com.android.djlmapp.tools.other.TextUtil;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.bumptech.glide.Glide;
import com.feihong.zhiwenlibrary.dialog.DJLM_PasswordDialog;
import com.feihong.zhiwenlibrary.dialog.PasswordDialogListener;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class SelectNumAttestationActivity extends BaseActivity {

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.tv_sim)
    TextView tvSim;
    @BindView(R.id.sim_num)
    EditText simNum;
    @BindView(R.id.tv_sys)
    TextView tvSys;
    @BindView(R.id.xhrz_cl_sim)
    ConstraintLayout xhrzClSim;
    @BindView(R.id.tv_imei)
    TextView tvImei;
    @BindView(R.id.kk_tv_imei)
    TextView kkTvImei;

    @BindView(R.id.tv_xzhm)
    TextView tvXzhm;
    @BindView(R.id.kk_tv_xzhm)
    TextView kkTvXzhm;
    @BindView(R.id.cl_select_num)
    ConstraintLayout clSelectNum;
    @BindView(R.id.tv_tcmc)
    TextView tvTcmc;
    @BindView(R.id.kk_tv_tcmc)
    TextView kkTvTcmc;
    @BindView(R.id.cl_select_tc)
    ConstraintLayout clSelectTc;
    @BindView(R.id.tv_sxsj)
    TextView tvSxsj;
    @BindView(R.id.kk_tv_sxsj)
    TextView kkTvSxsj;
    @BindView(R.id.tv_tcprice)
    TextView tvTcprice;
    @BindView(R.id.kk_money)
    TextView kkMoney;
    @BindView(R.id.kk_eye)
    ImageView kkEye;
    @BindView(R.id.kk_qianming_photo)
    ImageView kkQianmingPhoto;
    @BindView(R.id.tv_smrz)
    TextView tvSmrz;
    @BindView(R.id.kk_tv_smrz)
    TextView kkTvSmrz;
    @BindView(R.id.cl_shiming)
    ConstraintLayout clShiming;
    @BindView(R.id.tv_smname)
    TextView tvSmName;
    @BindView(R.id.kk_tv_name)
    TextView kkTvName;
    @BindView(R.id.kk_cl_name)
    ConstraintLayout kkClName;
    @BindView(R.id.tv_cardnum)
    TextView tvCardnum;
    @BindView(R.id.kk_tv_cardnum)
    TextView kkTvCardnum;
    @BindView(R.id.kk_cl_cardnum)
    ConstraintLayout kkClCardnum;
    @BindView(R.id.kk_iv_photo)
    ImageView kkIvPhoto;
    @BindView(R.id.tv_lxhm)
    TextView tvLxhm;
    @BindView(R.id.ll_tv_lxhm)
    EditText llTvLxhm;
    @BindView(R.id.cl_qianming)
    ConstraintLayout clQianming;
    @BindView(R.id.cl_bianma)
    ConstraintLayout clBianMa;
    @BindView(R.id.cl_smrz_item)
    ConstraintLayout shiMingItem;
    @BindView(R.id.cb_xieyi)
    CheckBox cbXieyi;
    @BindView(R.id.tv_ltxy)
    TextView tvLtxy;
    @BindView(R.id.scroll)
    ScrollView scroll;
    @BindView(R.id.kk_tv_submit)
    TextView kkTvSubmit;
    @BindView(R.id.ll_selecttc_item)
    LinearLayout llSelecttcItem;

    private String jiTuanNum = ""; // 集团编码
    private String heYueId = ""; // 合约id
    private String imeiNo = ""; // imei号
    private String yeWuType = ""; // 开界面传过来,业务类型
    private String addPara = ""; // addPara


    private String selectPhoneNum = ""; // 选择的号码
    private String bluetoothName = ""; // 蓝牙设备名称
    private String specPrice = ""; // 眼睛松开显示价格
    private String dpPrice = ""; // 眼睛按住显示价格
    private String specId = "";
    private String sName = ""; // 签名url
    private String sFlag = "";  // 是否签名
    private String sMoney = ""; // 签名带回的金额
    private String keyvalue = ""; // SIM卡输入内容
    private int phot_lists = 0; // 用户上传的照片(正,反,手持,公安)

    private CommonPopupWindow window;
    private ListView popList;
    private GetSimNumAdapter popAdapter;
    private LayoutGravity layoutGravity;
    private PopupWindow popupWindow;
    private ArrayList<SimNumInfo.IccidListBean> simlist = new ArrayList<>();
    private StringBuilder stringBuilder;
    private String face_image = "";
    private String face_ok = "";
    private String sfz_card = "";
    private String sfz_name = "";
    private String sfzPhoto = "";
    private String typeId = "";
    private String guHuaNum = "";
    private String paySucUrl = "";
    private String fkblNum = "";

    private boolean isShow = false; // 防止获取不到位置重复显示键盘
    private String hzAddress = "";
    private String hzTime = "";
    private String hzSex = "";
    private String idcardType = "1";
    private String iccidNum;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (passwordDialog != null) {
                passwordDialog.dismiss();
            }
            EventBusUtil.sendEvent(new Event<String>(EventCodes.EventKaiKaCode.D));

            switch (msg.what) {
                case 0:
                    // 跳转首页
                    startActivity(new Intent(SelectNumAttestationActivity.this, OrderListActivity.class));
                    finish();
                    break;
                case 1:
                    // 跳转web转订单
                    Intent intent1 = new Intent(SelectNumAttestationActivity.this,
                            PaySuccessActivity.class);
                    intent1.putExtra("sucUrl", paySucUrl);
                    startActivity(intent1);
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_num_attestation);
        ButterKnife.bind(this);
        initView();
        initData();
        creatPopupWindow(); // 创建SIM卡窗口

    }

    @Override
    protected void initView() {
        PrefUtils.putString("FACE_TOKEN", ""); // 置空新活体检测保存的数据
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.VISIBLE);
        tvName.setText("选号认证");

        clBianMa.setVisibility(View.GONE);

        yeWuType = getIntent().getStringExtra("YEWUTYPE"); // 业务类型

        jiTuanNum = getIntent().getStringExtra("JTBM"); // 集团编码

        heYueId = getIntent().getStringExtra("HEYUEID"); // 合约机
        imeiNo = getIntent().getStringExtra("IMEINO");// 合约机

        guHuaNum = getIntent().getStringExtra("GHHM");// 固话addPara
        addPara = getIntent().getStringExtra("ADDPARA"); // 固话addPara

        fkblNum = getIntent().getStringExtra("FKBL_NUM"); // 副卡办理

        if (TextUtils.isEmpty(yeWuType)) {
            yeWuType = "";
        }
        if (TextUtils.isEmpty(jiTuanNum)) {
            jiTuanNum = "";
        }
        if (TextUtils.isEmpty(imeiNo)) {
            imeiNo = "";
        }
        if (TextUtils.isEmpty(heYueId)) {
            heYueId = "";
        }
        if (TextUtils.isEmpty(guHuaNum)) {
            guHuaNum = "";
        }
        if (TextUtils.isEmpty(addPara)) {
            addPara = "";
        }
        if (TextUtils.isEmpty(fkblNum)) {
            fkblNum = "";
        }


        setBianMa(jiTuanNum, "集团编码");
        setBianMa(imeiNo, "IMEI编码");
        setBianMa(guHuaNum, "固话号码");
        setBianMa(fkblNum, "主卡号码");

        // 防止scrollView 的子控件自动滑到 底部或者中间部分
        scroll.setFocusable(true);
        scroll.setFocusableInTouchMode(true);
        // 防止ScrollView起始位置不是最顶部
        scroll.requestFocus();
    }

    @Override
    protected void initData() {
        stringBuilder = new StringBuilder();

        simNum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    if (simlist != null && simlist.size() > 0) {
                        //要先让popupwindow获得焦点，才能正确获取popupwindow的状态
//                        popupWindow.setFocusable(true);
                        // popupwindow处于显示状态,可以关闭
                        simlist.clear();
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }
                    }
                }
            }
        });

        simNum.addTextChangedListener(phoneTextW);  //监听输入框变化
        simNum.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:

                        break;
                    case MotionEvent.ACTION_UP:
                        Log.e("项目异常ACTION_UP", "------ACTION_UP------" + simlist.size());
                        if (simlist != null && simlist.size() > 0) {
                            simlist.clear();
                            //要先让popupwindow获得焦点，才能正确获取popupwindow的状态
//                    popupWindow.setFocusable(true);
                            // popupwindow处于显示状态,可以关闭
                            if (popupWindow.isShowing()) {
                                popupWindow.dismiss();
                            }
                        } else {
                            keyvalue = simNum.getText().toString().trim();
                            if (TextUtils.isEmpty(keyvalue)) {
                                keyvalue = "";
                            }
                            // 处于关闭状态,可以显示
                            window.showBashOfAnchor(simNum, layoutGravity, 0, 0);
                            getSimNumData(keyvalue);
                        }
                        scroll.requestDisallowInterceptTouchEvent(true);
                        break;
                }
                return false;
            }
        });

        // 点击眼睛按钮，按下和抬起需要改变数据
        kkEye.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    // 号码虚拟价格= 号码价格和虚拟靓号费全大值
                    case MotionEvent.ACTION_DOWN:
                        // 按住事件发生后执行代码的区域
                        kkMoney.setText(dpPrice);
                        scroll.requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_UP:
                        // 松开事件发生后执行代码的区域
                        kkMoney.setText(specPrice);
                        scroll.requestDisallowInterceptTouchEvent(true);
                        break;
                }
                return true;
            }
        });

    }

    private void setBianMa(String bianMa, String title) {

        if (bianMa != null && !TextUtils.isEmpty(bianMa)) {
            Log.e("项目异常", bianMa + "------setBianMa------" + title);
            clBianMa.setVisibility(View.VISIBLE);
            tvImei.setText(title);
            kkTvImei.setText(bianMa);
        }
    }

    @OnClick({R.id.tv_sys, R.id.cl_select_num, R.id.tv_ltxy,
            R.id.cl_select_tc, R.id.kk_eye, R.id.cl_shiming, R.id.cl_qianming, R.id.kk_tv_submit})
    public void onViewClicked(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        switch (view.getId()) {
            case R.id.tv_sys: // 扫一扫
                Intent intent = new Intent(SelectNumAttestationActivity.this,
                        TiaoXingCodeScanerActivity.class);
                startActivityForResult(intent, 1314);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
                break;
            case R.id.cl_select_num: // 选择号码
                keyvalue = simNum.getText().toString().trim();
                if (!TextUtils.isEmpty(keyvalue)) {
                    isJump = true;
                    getSimNumData(keyvalue);
                } else {
                    ToastUtils.showShortToast(SelectNumAttestationActivity.this, "请先选择号码");
                }
                break;
            case R.id.cl_select_tc: // 选择套餐
//                Intent intent = new Intent(SelectNumActivity.this, SelectTaoCanActivity.class);
//                intent.putExtra("phoneNum", phonenum);
//                intent.putExtra("virtual_price", virtual_price);
//                intent.putExtra("region", region);
//                intent.putExtra("k2", k2);
//                intent.putExtra("ICCIDNO", simNum);
//                intent.putExtra("JTBM", jiTuanNum);
//                intent.putExtra("HEYUEID", heYueId);
//                intent.putExtra("ADDPARA", addPara);
//                intent.putExtra("YEWUTYPE", yeWuType);
//                startActivity(intent);
                break;
            case R.id.kk_eye: // 眼睛
                break;
            case R.id.cl_shiming: //实名认证
                if (llSelecttcItem.getVisibility() == View.VISIBLE) {
                    startActivity(new Intent(SelectNumAttestationActivity.this, ShiMingRengZhengActivity.class)
                            .putExtra("CHENGKAJIHUO", 1).putExtra("SPECID", specId).putExtra("selectPhoneNum", selectPhoneNum));
                } else {
                    ToastUtils.showShortToast(SelectNumAttestationActivity.this, "请先选择套餐");
                }
                break;
            case R.id.cl_qianming: // 签名
                startActivityForResult(new Intent(SelectNumAttestationActivity.this, QianMingActivity.class), 1314);
                break;
            case R.id.tv_ltxy: // 联通协议
                // 联通协议
                startActivity(new Intent(SelectNumAttestationActivity.this,
                        LianTongXieYiListActivity.class));
                break;
            case R.id.kk_tv_submit: // 提交
                isShow = false;
                kkTvSubmit.setEnabled(false);
                if (isSubmit()) {
                    SelectNumAttestationActivityPermissionsDispatcher.openCameraWithCheck(this);
//                    getLocationPrem();
                } else {
                    kkTvSubmit.setEnabled(true);
                }
                break;
        }
    }

    /**
     * 判断能否提交订单
     */
    private boolean isSubmit() {
        boolean isSubMit = false;
        String trim = llTvLxhm.getText().toString().trim();

        if (!TextUtils.isEmpty(typeId) && typeId != null) {
            if (!TextUtils.isEmpty(sfz_card) && sfz_card != null) {
                if (!TextUtils.isEmpty(trim)) {
                    boolean matches = TextUtils.isDigitsOnly(trim);
                    Log.e("项目异常matches", trim.length() + "------matches------" + matches);
                    if (matches && trim.length() == 11) {
                        if ("1".equals(sFlag)) {
                            // 先判断权限
                            // showContacts();
                            if (cbXieyi.isChecked()) {
                                isSubMit = true;
                            } else {
                                ToastUtils.showShortToast(SelectNumAttestationActivity.this,
                                        "请阅读开卡相关协议并同意");
                            }
                        } else {
                            ToastUtils.showShortToast(SelectNumAttestationActivity.this,
                                    "请先签名");

                        }
                    } else {
                        ToastUtils.showShortToast(SelectNumAttestationActivity.this,
                                "联系电话格式有误");
                    }

                } else {
                    ToastUtils.showShortToast(SelectNumAttestationActivity.this,
                            "请输入联系电话");
                }
            } else {
                ToastUtils.showShortToast(SelectNumAttestationActivity.this,
                        "请先实名认证");
            }
        } else {
            ToastUtils.showShortToast(SelectNumAttestationActivity.this,
                    "请先选择号码和套餐");
        }
        return isSubMit;

    }


    /**
     * 提交订单
     */
    private void submitOrder(String password, String touch_pwd, String touch_num) {
        String aid = PrefUtils.getString(ConstantsValue.SELECTNUM_AID, ""); // 号码编码--号码列表
        String jbr_idnum = PrefUtils.getString("JBR_IDNUM", ""); // 获取经办人身份证号
        String face_token = PrefUtils.getString("FACE_TOKEN", ""); // 获取新活体检测数据
        String mobile = llTvLxhm.getText().toString().trim(); // 联系号码
        MyApplication.getInstance().getHttpTools().submitKaiKa(hzTime, idcardType, hzSex, hzAddress,
                sfz_name, phot_lists, fkblNum, addPara, mobile, bluetoothName, face_image, face_ok,
                face_token, longitude + "", latitude + "", keyvalue, aid, imeiNo, heYueId, jiTuanNum,
                jbr_idnum, specId, typeId, sfz_card, sfz_name, sName, password, touch_pwd, touch_num,
                yeWuType, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            parseSubmitJson(response.body());
                        } catch (Exception e) {
                            e.printStackTrace();
                            passwordDialog.setState(R.mipmap.pay_er, "支付失败1");
                            ToastUtils.showShortToast(SelectNumAttestationActivity.this, "数据解析异常");
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        // 显示支付失败
                        passwordDialog.setState(R.mipmap.pay_er, "支付失败2");
                        ToastUtils.showShortToast(SelectNumAttestationActivity.this, "网络或服务器错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });

    }

    private void parseSubmitJson(String json) {
        Gson gson = new Gson();
        Info info = gson.fromJson(json, Info.class);

        if (info != null) {
            int code = info.getCode();
            if (TextUtils.isEmpty(info.getMsg())) {
                passwordDialog.setState(R.mipmap.pay_er, "提交失败:" + code);
                return;
            }
            if (code < 1000) { // web
                // 显示支付成功
                passwordDialog.setState(R.mipmap.pay_su, "支付成功");
                paySucUrl = info.getUrl();

                handler.sendEmptyMessageDelayed(1, 1000);

            } else if (code > 6999 && code < 8001) {
                // 跳到订单界面
                passwordDialog.setState(R.mipmap.pay_er, info.getMsg());

                handler.sendEmptyMessageDelayed(0, 1000);
            } else if (code == 3001) {
                // 显示订单提交失败
                passwordDialog.setState(R.mipmap.pay_er, info.getMsg());
            } else {
                // 显示订单提交失败

                passwordDialog.setState(R.mipmap.pay_er, info.getMsg());

            }
        } else {
            passwordDialog.setState(R.mipmap.pay_er, "提交返回数据为空");
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        // 注册eventbus
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        // 接受到Event后的相关逻辑
        switch (event.getCode()) {
            case EventCodes.EventKaiKaCode.B: // 套餐
                SeleTcInfo data2 = (SeleTcInfo) event.getData();
                if (data2 != null) {
                    dpPrice = data2.getDp_price();
                    specPrice = data2.getSpec_pric();
                    String phonePrice = data2.getPhone_price();
                    String price = data2.getPrice();
                    String show_parms = data2.getShow_parms();
                    String spec_g_id = data2.getSpec_g_id();
                    specId = data2.getSpec_id1();
                    String specName = data2.getSpec_name();
                    String spec_type = data2.getSpec_type();
                    String type_num = data2.getType_num();

                    String phoneNum = data2.getPhoneNum();
                    selectPhoneNum = phoneNum;
                    String msg = data2.getMsg();
                    typeId = data2.getType_id();
                    Log.e("项目异常specId", "------specId------" + specId);

                    String virtualPrice = PrefUtils.getString(ConstantsValue.SELECTNUM_VIRTUAL_PRICE, "");

                    llSelecttcItem.setVisibility(View.VISIBLE);
                    kkTvSmrz.setText("请扫描进行认证");
                    shiMingItem.setVisibility(View.GONE);

                    kkTvTcmc.setText(specName);
                    kkTvTcmc.setTextColor(Color.BLACK);

                    tvTcprice.setText(price + "元,含" + phonePrice + "话费" + "+此号靓号费为" + virtualPrice + "元");
                    tvTcprice.setTextColor(Color.BLACK);

                    kkTvSxsj.setText(msg);
                    kkTvSxsj.setTextColor(Color.BLACK);

                    kkTvXzhm.setText(phoneNum);
                    kkTvXzhm.setTextColor(Color.BLACK);
                    kkMoney.setText(specPrice);
                }
                break;
            case EventCodes.EventFaceCode.A: // 实名认证
                phot_lists = PrefUtils.getInt("PHOT_LISTS", 0); // 用户上传的照片(正,反,手持,公安)
                FaceRzInfo data3 = (FaceRzInfo) event.getData();
                if (data3 != null) {
                    face_image = data3.getFace_image();
                    face_ok = data3.getFace_ok();
                    sfz_card = data3.getSfz_card();
                    sfz_name = data3.getSfz_name();
                    sfzPhoto = data3.getSfzPhoto();
                    hzAddress = data3.getAddress();
                    hzTime = data3.getTime();
                    hzSex = data3.getSex();
                    if (!TextUtils.isEmpty(hzAddress) && !TextUtils.isEmpty(hzTime) && !TextUtils.isEmpty(hzSex)) {
                        idcardType = "2";
                    }

                    if (!"1".equals(face_ok) && !"2".equals(face_ok)) {
                        kkTvSmrz.setText("请扫描进行认证");
                        shiMingItem.setVisibility(View.GONE);
                        return;
                    }

                    if ("1".equals(face_ok)) {
                        kkTvSmrz.setText("已认证");
                        bluetoothName = PrefUtils.getString("BluetoothName", "");
                    } else if ("2".equals(face_ok)) {
                        kkTvSmrz.setText("待审核");
                        bluetoothName = PrefUtils.getString("BluetoothName", "");
                    }
                    shiMingItem.setVisibility(View.VISIBLE);
                    kkTvSmrz.setTextColor(Color.BLACK);
                    kkTvName.setText(sfz_name);
                    kkTvCardnum.setText(sfz_card);
                    // 加载身份证照片
                    if (!TextUtils.isEmpty(sfzPhoto)) {
                        Glide.with(SelectNumAttestationActivity.this).load(sfzPhoto).into(kkIvPhoto);
                    } else {
                        kkIvPhoto.setImageBitmap(null);
                    }
                }

                break;
        }
    }

    private boolean isJump = false;

    /**
     * 判断是否需要跳转界面
     */
    private void getSimNumData(String editValue) {
        if (isJump) {
            // 如果是跳转界面就在点击完成后禁用点击事件
            kkTvXzhm.setEnabled(false);
        }
        MyApplication.getInstance().getHttpTools().getSimNum("", fkblNum, addPara, editValue, yeWuType,
                new StringCallback() {

                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            parseSimNumJson(response.body(), isJump);
                        } catch (Exception e) {
                            e.printStackTrace();
                            if (popupWindow != null && popupWindow.isShowing()) {
                                popupWindow.dismiss();
                            }
                            ToastUtils.showShortToast(SelectNumAttestationActivity.this, "数据解析异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }
                        ToastUtils.showShortToast(SelectNumAttestationActivity.this, "网络或服务器错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        kkTvXzhm.setEnabled(true);
                    }
                });
    }

    /**
     * @param json
     * @param isJump 判断是否需要跳转界面
     */
    private void parseSimNumJson(String json, boolean isJump) {
        Log.e("项目异常", "------parseSimNumJson------" + json);
        Gson gson = new Gson();
        SimNumInfo simNumInfo = gson.fromJson(json, SimNumInfo.class);
        if (simNumInfo != null) {
            int code = simNumInfo.getCode();
            if (code == 300) {
                simlist.clear(); // 每次输入的时候，重新初始化数据列表
                simlist.addAll(simNumInfo.getIccid_list()); // 添加SIM卡数据
                if (simlist != null && simlist.size() > 0) {
                    if (isJump) {
                        yanZhengSimNum(); // 验证sim卡号
                    } else {
                        popAdapter.setData(simlist);
                    }
                } else {
                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                    ToastUtils.showShortToast(SelectNumAttestationActivity.this, "未检测到可用SIM卡");
                }
            } else {
                ToastUtils.showLongToast(SelectNumAttestationActivity.this,
                        simNumInfo.getMsg());
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        } else {
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            ToastUtils.showShortToast(SelectNumAttestationActivity.this, "未获取到数据");
        }
    }

    /**
     * 验证sim卡号
     */
    private void yanZhengSimNum() {
        for (SimNumInfo.IccidListBean entity : simlist) {
            stringBuilder.append(entity.getKey() + entity.getNum());
        }
        if (stringBuilder.toString().contains(keyvalue)) {
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            Log.e("项目异常simNum", "------yanZhengSimNum------" + keyvalue);
//            llSelecttcItem.setVisibility(View.GONE);
//            shiMingItem.setVisibility(View.GONE);
//            kkTvTcmc.setText("选择号码后确定套餐");
            // 选择号码
            Intent intent = new Intent(SelectNumAttestationActivity.this
                    , SelectNumActivity.class);
            intent.putExtra("YEWUTYPE", yeWuType);
            intent.putExtra("ICCIDNO", keyvalue);
            intent.putExtra("JTBM", jiTuanNum);
            intent.putExtra("HEYUEID", heYueId);
            intent.putExtra("ADDPARA", addPara);
            intent.putExtra("FKBL_NUM", fkblNum);
            startActivity(intent);
        } else {
            ToastUtils.showShortToast(SelectNumAttestationActivity
                    .this, "该SIM卡不可用");
        }
    }

    /**
     * 创建popupwindow
     * https://www.cnblogs.com/jzyhywxz/p/7039503.html
     */
    private void creatPopupWindow() {
        int PopWidth = GlobalUtils.getScreenWidth(SelectNumAttestationActivity.this);
        int PopHeight = GlobalUtils.getScreenHeight(SelectNumAttestationActivity.this);
        PopWidth = (int) Math.rint(PopWidth / 1.6);
        PopHeight = (int) Math.rint(PopHeight / 2.2);
        window = new CommonPopupWindow(SelectNumAttestationActivity.this, R.layout.pop_select_list,
                PopWidth, PopHeight) {
            @Override
            protected void initView() {
                View contentView = getContentView();
                popList = contentView.findViewById(R.id.pop_list);
                popAdapter = new GetSimNumAdapter(SelectNumAttestationActivity.this);
                popAdapter.setData(simlist);
                popList.setAdapter(popAdapter);
            }

            @Override
            protected void initEvent() {
                popList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (simlist != null && simlist.size() > 0) {
                            iccidNum = simlist.get(position).getNum();
                            simNum.setText(iccidNum);
                            yanZhengSimNum();
                        }
                        if (popupWindow != null && popupWindow.isShowing()) {
                            popupWindow.dismiss();
                        }

                    }
                });
            }

            @Override
            protected void initWindow() {
                super.initWindow();

            }
        };
        popupWindow = window.getPopupWindow();

        // 防止键盘影响
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                return true;
            }
        });
        /**
         * 触摸popwindow 隐藏弹出框
         */
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                im.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), 0);
                return false;
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Log.e("项目异常", "------onDismiss------" + "");
                simlist.clear();
            }
        });
        // 设置显示位置属性
        layoutGravity = new LayoutGravity(LayoutGravity.CENTER_HORI | LayoutGravity.TO_BOTTOM);

//        window.showBashOfAnchor(view, layoutGravity, 0, 0); // 显示在控件下方
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1314) {
            switch (resultCode) {
                case 0:
                    if (data != null) {
                        Bundle str = data.getExtras();
                        if (str != null) {
                            String result = str.getString(CodeUtils.RESULT_STRING);
                            int resultType = str.getInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
                            switch (resultType) {
                                case CodeUtils.RESULT_SUCCESS:
                                    if (result != null) {
                                        if (result.length() == 19) {
                                            keyvalue = result.substring(0, 19);
                                            if (TextUtil.isNumeric(keyvalue)) {
                                                // 是纯数字
                                                simNum.setText(keyvalue);
                                                isJump = true;
//                                            getSimNumData(keyvalue, true);
                                            } else {
                                                ToastUtils.showShortToast(SelectNumAttestationActivity.this, "请确定您扫描的是SIM卡1");
                                                kkTvXzhm.setText("");
                                            }
                                        } else {
                                            ToastUtils.showShortToast(SelectNumAttestationActivity.this, "请确定您扫描的是联通SIM卡");
                                            kkTvXzhm.setText("");
                                        }
                                    } else {
                                        ToastUtils.showShortToast(SelectNumAttestationActivity.this, "扫描失败，请重新扫描1");
                                    }
                                    break;
                                case CodeUtils.RESULT_FAILED:
                                    ToastUtils.showShortToast(SelectNumAttestationActivity.this, "扫描失败，请重新扫描2");
                                    break;
                            }
                        }
                    }
                    break;
                case 2:
                    if (data != null) {
                        // 签名url
                        sName = data.getStringExtra("fileName");
                        // 是否签名
                        sFlag = data.getStringExtra("signFlag");
                        // 签名带回的金额
                        sMoney = data.getStringExtra("signMoney");

                        Log.e("项目异常", "----getStringExtra--sMoney------" + sMoney);
                        Log.e("项目异常", "----getStringExtra--sName------" + sName);
                        if (!TextUtils.isEmpty(sName)) {
                            // 加载签名照片
                            ImageLoader.getInstance()
                                    .displayImage(sName, kkQianmingPhoto, new DisplayImageOptions.Builder()
                                            .cacheInMemory(true)//默认会在内存缓存
                                            .cacheOnDisk(true)//默认会在硬盘缓存
                                            .displayer(new FadeInBitmapDisplayer(1000)).build());
                        }
                    } else {
                        ToastUtils.showShortToast(SelectNumAttestationActivity.this, "未获取到签名");
                    }
                    break;
            }
        }
    }

    private double latitude = 0; // 纬度
    private double longitude = 0; // 经度
    private DJLM_PasswordDialog passwordDialog;

    /**
     * 初始化密码键盘
     */
    private void initKeyBord() {
        passwordDialog = new DJLM_PasswordDialog(SelectNumAttestationActivity.this);
        passwordDialog.setCallBack(new PasswordDialogListener() {
            @Override
            public void onDoneInput(DJLM_PasswordDialog dialog, String pwd) {
                passwordDialog.showLoadingView();
                submitOrder(pwd, "", "");
            }

            @Override
            public void successFinger(DJLM_PasswordDialog dialog) {
                passwordDialog.showLoadingView();
                String touch_pwd = PrefUtils.getString(ConstantsValue.ZHIWEN_KEY, "");
                String num = (System.currentTimeMillis() + "").substring(3);
                String newpwd = MD5Util.MD5("DJLM_TOUCH_PAY" + num +
                        UserInfoUtils.getUserInfoUtilsInstance().getToken() + touch_pwd).toLowerCase();
                submitOrder(Constants.getZhiWenNewPwd(SelectNumAttestationActivity.this),
                        Constants.getZhiWenTouchPwd(SelectNumAttestationActivity.this),
                        Constants.zhiWenNum);
            }

            @Override
            public void onBtnClick(int type) {
                if (type == 1) {
                    //加款按钮点击
                    startActivity(new Intent(SelectNumAttestationActivity.this, AddMoneyActivity.class));
                } else if (type == 2) {
                    //忘记密码按钮点击
                    startActivity(new Intent(SelectNumAttestationActivity.this, ForgetPwdActivity.class));
                }
            }
        });
    }

    /**
     * 弹出自定义输入键盘
     */
    private void showKeyBoard() {
        kkTvSubmit.setEnabled(true);
        initKeyBord(); // 初始化密码键盘
        passwordDialog.show(getSupportFragmentManager(), "支付");
        if (PrefUtils.getBoolean(ConstantsValue.ZHIWEN_STATE, false)
                && !TextUtils.isEmpty(PrefUtils.getString(ConstantsValue.ZHIWEN_KEY, ""))) {
            if (passwordDialog.isFingerprintEnable()) {
                passwordDialog.setEnableFinger(true);
            } else {
                passwordDialog.setEnableFinger(false);
            }

        } else {
            passwordDialog.setEnableFinger(false);
        }
        //设置余额
        passwordDialog.setYue(sMoney);
    }

    TextWatcher phoneTextW = new TextWatcher() { // EditText变化监听

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.e("项目异常simNum", "------afterTextChanged------" + s.toString());

            keyvalue = simNum.getText().toString();

            //将光标移至文字末尾
            simNum.setSelection(keyvalue.length());
//            if (!TextUtils.isEmpty(keyvalue)) {
                boolean activityExist = MyActivityManager.isActivityExist(getActivity());
                Log.e("项目异常", "-----activityExist------" + activityExist);
                if (activityExist) {
                    if (window != null) {
                        window.showBashOfAnchor(simNum, layoutGravity, 0, 0);
                        getSimNumData(keyvalue);
                    }
                }
//            } else {
//                if (popupWindow != null && popupWindow.isShowing()) {
//                    popupWindow.dismiss();
//                }
//            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        simlist.clear(); // 防止触摸判断的时候不显示弹窗
    }

    @Override
    protected void onDestroy() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
        super.onDestroy();
    }


    //=======================================请求定位权限=======================================

    /**
     * 获取位置信息
     */
    private void getLocationPrem() {
        showKeyBoard();
        // 获取经纬度
        try {
            OnceLocationTools locationTools = new OnceLocationTools(SelectNumAttestationActivity.this,
                    new LocationCallBack() {
                        @Override
                        public void successGetLocation(LocationInfo info) {
                            //定位成功
                            latitude = info.getLatitude();
                            longitude = info.getLongitude();

                        }

                        @Override
                        public void error(String error) {
                            latitude = 0.0;
                            longitude = 0.0;
                            if (!isShow) {
                                isShow = true; // 第一次进入就改变状态,防止再次进入,在点击的时候重置状态

                            }
                        }
                    });
            locationTools.startLocation();//开始定位
        } catch (NullPointerException ex) {
            latitude = 0.0;
            longitude = 0.0;

        }
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void openCamera() {
        // 获取手机信息
        Log.e("项目异常", "openCamera权限: =================");
        getLocationPrem();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SelectNumAttestationActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获手机定位权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void denied() {
        Log.e("权限", "------denied------");
        //        loginBtnLogin.setEnabled(true);
        // 获取手机信息
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("项目异常", "denied权限: =================");
                getLocationPrem();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void askAgain() {
        Log.e("权限", "------askAgain------");
        //        loginBtnLogin.setEnabled(true);
        // 获取手机信息
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("项目异常", "askAgain权限: =================");
                getLocationPrem();
            }
        });
    }
}
